package com.example.a321.rxnetdemo;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by zhangdongyang on 2016/9/5.
 * Email:dongyangzhang@foxmail.com
 */
public class DemoService {
//    public static final String BASE_TRC_URL = "http://web.juhe.cn:8080/";
    public static final String BASE_TRC_URL = "https://test.api.liuyang.com/";
    private static OkHttpClient client;
    private static Retrofit retrofit;

    public static OkHttpClient getClient() {
        if (client == null) {
            X509TrustManager xtm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    X509Certificate[] x509Certificates = new X509Certificate[0];
                    return x509Certificates;
                }
            };

            SSLContext sslContext = null;
            try {
                sslContext = SSLContext.getInstance("SSL");

                sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());

            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            }
            HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            File httpCacheDirectory = new File(MainActivity.instance.getCacheDir(), "cache_file");
            Logger.d(httpCacheDirectory.exists());
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            client = new OkHttpClient.Builder()
                    .addInterceptor(httpLoggingInterceptor).sslSocketFactory(sslContext.getSocketFactory()).hostnameVerifier(DO_NOT_VERIFY)
                    .addNetworkInterceptor(new StethoInterceptor())
                    .cache(new Cache(httpCacheDirectory, 10 * 1024 * 1024)) // 10 MB
                    .addInterceptor(chain -> {
                        Request request = chain.request();
                        if (isNetworkAvailable(MainActivity.instance)) {
                            request = request.newBuilder().header("Cache-Control", "public, max-age=" + 10)
                                    .header("Content-Type", "application/json;charset=UTF-8")
                                    .header("Authorization", "bearer 6aa07f21a70b43fe8d1589072e9d9185")
                                    .build();
                        } else {
                            request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7)
                                    .header("Content-Type", "application/json;charset=UTF-8")
                                    .header("Authorization", "bearer 6aa07f21a70b43fe8d1589072e9d9185")
                                    .build();
                        }
                        return chain.proceed(request);
                    }).build();
        }
        return client;
    }

    private static Retrofit getRetrofit() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_TRC_URL)
                    .client(getClient())
//                    .addCallAdapterFactory(RxErrorHandlingCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        }
        return retrofit;
    }

    public static DemoApi createDemoService() {
        return getRetrofit().create(DemoApi.class);
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();
    }
}
